import React, { Component } from 'react'
import Highlighter from 'react-highlight-words'
import { history } from 'umi'
import {
  Icon,
  message,
  Button,
  Table,
  Divider,
  Tag,
  Popconfirm,
  Input,
  Tooltip,
  Upload,
  Spin,
  Switch,
} from 'antd'
import { getArticleList, delArticle, getTagInfo, changeArticleStatus } from '@/services/admin'
import './index.less'
import { articleBaseUrl } from '@/assets/js/ConstVariable.js'
import moment from 'moment'

export default class ArticleList extends Component {
  state = {
    list: [],
    searchText: '',
    searchedColumn: '',
    isListLoading: true,
    tagFilterList: [],
  }

  componentDidMount() {
    this.getArticleList()

    document.title = '文章列表'
  }
  // 获取文章列表
  getArticleList = async () => {
    const res = await getArticleList()
    const res2 = await getTagInfo()
    if (res?.status === 200 && res2?.status === 200) {
      message.destroy()
      message.success('获取文章列表成功')
      let tagFilterList = res2.tagList.map((item) => {
        return { text: item.tag_name, value: item.tag_name }
      })
      this.setState({ list: res.data, isListLoading: false, tagFilterList })
    }
  }
  // 删除文章
  handleDelete = async (id) => {
    const res = await delArticle(id)
    if (res?.status === 200) {
      message.success('删除文章成功~')
      this.getArticleList()
    }
  }
  // 编辑文章
  updateArticle = (id) => {
    sessionStorage.setItem('id', id)
    history.push('/admin/addarticle?id=' + id)
  }

  // 表格自定义过滤
  getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={(node) => {
            this.searchInput = node
          }}
          placeholder={`请输入标题`}
          value={selectedKeys[0]}
          onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: (filtered) => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex].toString().toLowerCase().includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select())
      }
    },
    render: (text, record) =>
      this.state.searchedColumn === dataIndex ? (
        <a href="" href={articleBaseUrl + '#/detail/' + record.id} target="_blank">
          <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 2 }}
            searchWords={[this.state.searchText]}
            autoEscape
            textToHighlight={text.toString()}
          />
        </a>
      ) : (
        <a href={articleBaseUrl + '#/detail/' + record.id} target="_blank">
          {text}
        </a>
      ),
  })

  // 搜索
  handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm()
    this.setState({
      searchText: selectedKeys[0],
      searchedColumn: dataIndex,
    })
  }

  // 重置
  handleReset = (clearFilters) => {
    clearFilters()
    this.setState({ searchText: '' })
  }
  render() {
    const { list, isListLoading, tagFilterList } = this.state
    const columns = [
      {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        width: 300,
        ellipsis: true,
        ...this.getColumnSearchProps('title'),
      },
      {
        title: '简介',
        dataIndex: 'introduce',
        key: 'introduce',
        render: (introduce) => <a className="introduce">{introduce}</a>,
      },
      {
        title: '发布时间',
        dataIndex: 'addTime',
        key: 'addTime',
        width: 160,
        render: (addTime) => <a>{moment(addTime * 1000).format('YYYY-MM-DD HH:ss')}</a>,
        sorter: (a, b) => moment(a.addTime * 1000).unix() - moment(b.addTime * 1000).unix(),
      },
      {
        title: '浏览次数',
        key: 'viewCount',
        dataIndex: 'viewCount',
        width: 120,
        render: (viewCount) => {
          let color = 'gray'
          if (viewCount > 2000) {
            color = 'tomato'
          } else if (viewCount > 1000) {
            color = 'volcano'
          } else if (viewCount > 500) {
            color = 'green'
          }
          return (
            <span>
              <Tag color={color}>{viewCount}</Tag>
            </span>
          )
        },
        sorter: (a, b) => a.viewCount - b.viewCount,
      },
      {
        title: '标签',
        key: 'tagName',
        dataIndex: 'tagName',
        width: 120,
        filters: tagFilterList,
        onFilter: (value, record) => record.tagName === value,
        render: (tagName, record, index) => {
          const colorArr = ['geekblue', 'green', 'tomato', 'skyblue', 'volcano']
          return (
            <span>
              <Tag>
                <Icon type={record.tagIcon} /> &nbsp;
                {tagName}
              </Tag>
            </span>
          )
        },
      },
      {
        title: '文章状态',
        key: 'status',
        dataIndex: 'status',
        filters: [
          {
            text: '已发布',
            value: 1,
          },
          {
            text: '未发布',
            value: 0,
          },
        ],
        onFilter: (value, record) => record.status === value,
        width: 150,
        render: (status, record) => {
          return (
            <span>
              <Switch
                defaultChecked={status === 1}
                onChange={(value) => {
                  changeArticleStatus(record.id, Number(value))
                }}
              />
            </span>
          )
        },
      },
      {
        title: '操作',
        key: 'content',
        width: 150,
        render: (text, record) => (
          <span>
            <a onClick={() => this.updateArticle(record.id)}>编辑</a>
            <Divider type="vertical" />
            <Popconfirm
              title="确认要删除吗？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => this.handleDelete(record.id)}
            >
              <a>删除</a>
            </Popconfirm>
          </span>
        ),
      },
    ]

    return (
      <div className="article-list">
        {isListLoading ? (
          <Spin />
        ) : (
          <Table
            bordered
            columns={columns}
            dataSource={this.state.list}
            rowKey={(record) => record.id}
          />
        )}
      </div>
    )
  }
}
